from . import setup
from . import constants as C
from threading import Thread
import pygame


class Clinet:
    def __init__(self):
        self.connection = setup.connection
        self.finished = False
        self.my_id = 0
        # self.get_connection()
        # thread = Thread(target=self.recv_data)
        # thread.setDaemon(True)
        # thread.start()

    def unpack_map_data(self, raw):

        if False == raw.startswith("snakes:"):
            print("数据错误")

        #把蛇和食物信息分开
        raw_snakes, raw_food = raw.split("food:")

        #把蛇的信息由string转为数字
        raw_snakes = raw_snakes[10:-3]  #移除前缀"snakes:[[("和后缀")]]"
        raw_snakes = raw_snakes.split(")],[(")

        snakes = []
        for i, snake in enumerate(raw_snakes):
            snake = snake.split("),(")
            single_snake = []
            for j, xy in enumerate(snake):
                xy = xy.split(",")
                x = int(xy[0])
                y = int(xy[1])
                xy = (x, y)
                single_snake.append(xy)
            snakes.append(single_snake)

        #把食物信息由string转为数字
        # print("test", raw_food[2:-2])
        raw_food = raw_food[2:-2]  #移除前缀："[(" 移除后缀：")]"
        raw_food = raw_food.split("),(")

        food = []
        for i, xy in enumerate(raw_food):
            xy = xy.split(",")
            x = int(xy[0])
            y = int(xy[1])
            xy = (x, y)
            food.append(xy)
        return snakes, food

    def get_connection(self):
        try:
            self.connection.connect((C.SERVER_IP, C.SERVER_PORT))
            print("连接成功")
            return True
        except:
            print("连接失败，退出游戏")
            self.connection.close()
            pygame.quit()
            quit()
